# -*- coding:utf-8 -*-

import golsee
from golsee import models
from golsee.Helpers import blog_render
from golsee import cache
import flask
import flask_login
from flask import g
import datetime
from . import forms


def index(categoryname='all', month='all', page=1):
    category = models.Category.query.filter_by(is_use=1).order_by(models.Category.seq)
    article = models.Article.article_per_page(categoryname, month, page)
    return blog_render("index.html",
                       title='Home',
                       article=article,
                       category=category,
                       categoryname=categoryname,
                       month=month)


@golsee.golsee.before_request
def before_request():
    g.search_form = forms.SearchForm()
    g.user = flask_login.current_user
    if g.user.is_authenticated():
        g.user.last_seen = datetime.datetime.now()
        golsee.db.session.add(g.user)
        golsee.db.session.commit()
    if flask.request.url.find('static') < 0 and flask.request.url.find('favicon.ico') < 0:
        agent = flask.request.headers['User-Agent']
        url = flask.request.base_url
        log = models.Visit_log(timestamp=datetime.datetime.now(),
                               ip=flask.request.remote_addr,
                               url=url,
                               agent=agent)
        golsee.db.session.add(log)
        golsee.db.session.commit()


def msg():
    return blog_render('main/msg.html')


# @cache.cached(unless=True)
def about():
    return blog_render('main/about.html')


@cache.cached(unless=True)
def calendar():
    return blog_render('main/calendor.html')


# 第一次访问从数据库中加载设置
@golsee.golsee.before_first_request
def SomeSetFromDb():
    from golsee import models
    from golsee import mymail

    MAIL_SERVER = str(models.Settings.query.filter_by(type='MAIL_SERVER').first().value)
    MAIL_PORT = int(models.Settings.query.filter_by(type='MAIL_PORT').first().value)
    MAIL_USE_TLS = eval(models.Settings.query.filter_by(type='MAIL_USE_TLS').first().value)
    MAIL_USE_SSL = eval(models.Settings.query.filter_by(type='MAIL_USE_SSL').first().value)
    MAIL_USERNAME = str(models.Settings.query.filter_by(type='MAIL_USERNAME').first().value)
    MAIL_PASSWORD = str(models.Settings.query.filter_by(type='MAIL_PASSWORD').first().value)
    ADMIN_EMAIL = str(models.Settings.query.filter_by(type='ADMIN').first().value)
    DEFAULT_THEME = str(models.Settings.query.filter_by(type='DEFAULT_THEME').first().value)
    golsee.golsee.config['MAIL_SERVER'] = MAIL_SERVER
    golsee.golsee.config['MAIL_PORT'] = MAIL_PORT
    golsee.golsee.config['MAIL_USE_TLS'] = MAIL_USE_TLS
    golsee.golsee.config['MAIL_USE_SSL'] = MAIL_USE_SSL
    golsee.golsee.config['MAIL_USERNAME'] = MAIL_USERNAME
    golsee.golsee.config['MAIL_PASSWORD'] = MAIL_PASSWORD
    golsee.golsee.config['DEFAULT_THEME'] = DEFAULT_THEME
    golsee.golsee.config['ADMIN_EMAIL'] = ADMIN_EMAIL
    mymail.init_app(golsee.golsee)




